let express = require("express");
let cors = require("cors");
let moment = require("moment")
let HB = require("./HB");
let fs = require("./HB/readFill.js")

let app = express();

app.use(express.static("./../src"));  //静态资源通过服务器访问

app.use(cors());
//配置post请求
app.use(express.urlencoded({ extended: false }));
app.use(express.json());
//注册接口
app.post("/reg", async function (req, res, next) {
    let userData = [
        req.body.user,
        req.body.pwd,
        req.body.phone,
        moment(Date.now()).format("YYYY-MM-DD")
    ]
    // console.log(userData);
    let sql = "INSERT INTO `userinfo` (`uName`,`uPwd`,`uPhone`,`createdate`) VALUES (?,?,?,?)";
    try {
        let result = await HB.exec(sql, userData);
        let flag = (result && result.affectedRows >= 1);
        let msg = {
            message: flag ? "注册成功" : "注册失败",
            code: flag ? 200 : 201
        };
        res.json(msg);
    } catch (error) {
        res.json({ message: "注册失败", err: error.message, code: 201 });
    }
})

//登录接口
app.post("/login", async function (req, res, next) {
    let userData = [
        req.body.user,
        req.body.pwd
    ]
    let sql = "SELECT `uId`,`uname`,`uphone`,`createdate` FROM `userinfo` WHERE `uname`=? AND `upwd`=? AND `status`=1"
    try {
        let result = await HB.exec(sql, userData);
        let flag = (result && result.length >= 1);
        let msg = {
            message: flag ? "登录成功" : "登录失败",
            code: flag ? 200 : 201
        }
        flag ? msg["data"] = result[0] : "";
        res.json(msg);
    } catch (error) {
        res.json({ message: "登录失败", err: error.message, code: 201 });
    }
})

//主页获得本地数据接口
app.get("/allshop", async function (req, res, next) {
    let data = await fs.getFile("./data/shopData.json");
    data = JSON.parse(data);
    res.json({
        message: "查询成功",
        code: 200,
        data
    })
})

//根据url 地址 获得商品id 然后查询商品信息 获得信息  渲染页面
app.get("/ckshop/:id", async function (req, res, next) {
    let sId = parseInt((req.params.id).split(":")[1]);
    let data = JSON.parse(await fs.getFile("./data/shopData.json"));
    let ckshopData = data.find(item => item.sId == sId);
    // console.log(ckshopData);
    res.json({
        message: "查询成功",
        code: 200,
        data: ckshopData
    })

})

//根据用户加入购物车商品信息 提交到 数据库，判断是否第一次提交
app.post("/addCarts", async function (req, res, next) {
    let addShopMsg = [
        req.body.uId,
        req.body.cName,
        req.body.cPrice,
        req.body.cNum,
        req.body.cType,
        req.body.cNum * req.body.cPrice,
        req.body.cImg,
        moment(Date.now()).format("YYYY-MM-DD HH:dd:ss")
    ]
    let params = [
        req.body.uId,
        req.body.cName
    ]
    let cartsSql = "SELECT * FROM `carts` WHERE `uId`=? AND `cName`=? AND `cStatus`=1";
    let cartsRes = await HB.exec(cartsSql, params);
    let cartsFlag = (cartsRes && cartsRes.length >= 1);
    if (cartsFlag) {  //为true 说明 有东西 就修改 否则 就没有 添加过
        let cartsType = JSON.parse(cartsRes[0].cType);
        let usersType = JSON.parse(req.body.cType);
        for (let i = 0; i < cartsType.length; i++) {
            cartsType[i].num = parseInt(usersType[i].num) + parseInt(cartsType[i].num);
        }
        let xgCartMsg = [
            req.body.cNum,
            JSON.stringify(cartsType),
            moment(Date.now()).format("YYYY-MM-DD HH:mm:ss"),
            req.body.uId,
            req.body.cName,
        ]

        let xgCartSql = "UPDATe `carts` SET `cNum`=cNum+? ,`cType`=?, `cTotalPic`=cNum*cPrice ,`cDate`=? WHERE `uId`=? AND `cName`=? AND `cStatus`=1"
        let xgCartRes = await HB.exec(xgCartSql, xgCartMsg);
        let xgCartFlag = (xgCartRes && xgCartRes.affectedRows >= 1);
        res.json({
            message: xgCartFlag ? "购买成功" : "购买失败",
            code: xgCartFlag ? 200 : 201,
        })
    } else {
        let addCartSql = "INSERT INTO `carts` (`uId`,`cName`,`cPrice`,`cNum`,`cType`,`cTotalPic`,`cImg`,`cDate`) VALUES (?,?,?,?,?,?,?,?)";
        let addCartRes = await HB.exec(addCartSql, addShopMsg);
        let addCartFlag = (addCartRes && addCartRes.affectedRows >= 1);
        res.json({
            message: addCartFlag ? "购买成功" : "购买失败",
            code: addCartFlag ? 200 : 201,
        })
    }

})

//根据用户名获得该用户购物车内所有商品
app.get("/getcarts", async function (req, res, next) {
    let params = [
        req.query.uId
    ];
    let sql = "SELECT * FROM `carts` WHERE `uId`=?  AND `cStatus`=1";
    let result = await HB.exec(sql, params);
    res.json({
        message: "查询成功",
        code: 200,
        data: result
    })
})

//购物车内修改商品
app.post("/xgCarts", async function (req, res, next) {
    let params = [
        req.body.uId,
        req.body.cName
    ]
    let cartsSql = "SELECT * FROM `carts` WHERE `uId`=? AND `cName`=? AND `cStatus`=1";
    let cartsRes = await HB.exec(cartsSql, params);
    let cartsType = JSON.parse(cartsRes[0].cType);
    let usersType = JSON.parse(req.body.cType);
    for (let i = 0; i < cartsType.length; i++) {
        for (let m = 0; m < usersType.length; m++) {
            if (usersType[m].type == cartsType[i].type) {
                // console.log(usersType[m].type, cartsType[i].type);
                cartsType[i].num = usersType[m].num;
                break;
            }
            cartsType[i].num = 0;
        }

    }
    let addShopMsg = [
        req.body.cNum,
        JSON.stringify(cartsType),
        moment(Date.now()).format("YYYY-MM-DD HH:dd:ss"),
        req.body.uId,
        req.body.cName,
    ]
    let xgCartSql = "UPDATe `carts` SET `cNum`=? ,`cType`=?, `cTotalPic`=cNum*cPrice ,`cDate`=? WHERE `uId`=? AND `cName`=? AND `cStatus`=1"
    let xgCartRes = await HB.exec(xgCartSql, addShopMsg);
    let xgCartFlag = (xgCartRes && xgCartRes.affectedRows >= 1);
    res.json({
        message: xgCartFlag ? "购买成功" : "购买失败",
        code: xgCartFlag ? 200 : 201,
    })
})
//删除整个商品接口
app.post("/dlCart", async function (req, res, next) {
    let data = [
        req.body.uId,
        req.body.cName
    ]
    let sql = "UPDATE `carts` SET `cStatus`=0 WHERE `uId`=? AND `cName`=? AND `cStatus`=1;"
    let result = await HB.exec(sql, data);
    let flag = (result && result.affectedRows >= 1);
    res.json({
        message: flag ? "删除成功" : "删除失败",
        code: flag ? 200 : 201,
    })
})


app.listen(8080, function () {
    console.log("服务器启动完毕！");
})
